package com.gx.smart.building.admin;

import com.gx.smart.lib.http.api.asynctask.CallBack;
import com.gx.smart.lib.http.api.asynctask.GrpcAsyncTask;
import com.gx.smart.lib.http.api.config.ApiConfig;
import com.gx.smart.lib_http.BuildConfig;
import com.huishi.gx.ib.grpc.lib.ib.admin.workorder.v1.AddWorkOrderEventReq;
import com.huishi.gx.ib.grpc.lib.ib.admin.workorder.v1.WorkOrderApiGrpc;
import com.huishi.gx.ib.grpc.lib.ib.admin.workorder.v1.WorkOrderResp;
import com.huishi.gx.ib.grpc.lib.ib.admin.workorder.v1.dto.WorkOrderEventDto;
import com.orhanobut.logger.Logger;

import java.util.concurrent.TimeUnit;

import io.grpc.ManagedChannel;

/**
 * @author: xiaosy
 * 时间: 2022/3/23
 * @Description: java类作用描述
 * @Version: 1.0
 **/
public class WorkOrderApiService {
    private String host = BuildConfig.JOYLIFE_GRPC_UAA_SERIVER_URL;
    private String port = "80";

    private WorkOrderApiService() {

    }

    public static WorkOrderApiService getInstance() {
        return SingleTonHolder.INSTANCE;
    }

    /**
     * 获取AuthStub  设置超时时间  8秒
     *
     * @param channel
     * @return
     */
    private WorkOrderApiGrpc.WorkOrderApiBlockingStub getStub(ManagedChannel channel) {
        return WorkOrderApiGrpc.newBlockingStub(channel)
                .withDeadlineAfter(ApiConfig.TIMEOUT_NETWORK, TimeUnit.SECONDS);

    }

    /**
     * 工单撤销
     *
     * @param callBack
     * @return
     */
    public GrpcAsyncTask<String, Void, WorkOrderResp> cancelTask(
            String workOrderId,
            CallBack<WorkOrderResp> callBack) {
        return new GrpcAsyncTask<String, Void, WorkOrderResp>(callBack) {
            @Override
            protected WorkOrderResp doRequestData(ManagedChannel channel) {
                AddWorkOrderEventReq message = AddWorkOrderEventReq.newBuilder()
                        .setWorkOrderEventDto(WorkOrderEventDto.newBuilder()
                                .setWorkOrderId(workOrderId)
                                .build())
                        .build();
                Logger.d(message);
                WorkOrderResp response = null;
                try {
                    response = getStub(channel).cancelTask(message);
                    Logger.d(response);
                } catch (Exception e) {
                    Logger.e(e, "cancelTask");
                }
                return response;
            }
        }.setHost(host).setPort(port).doExecute();
    }

    private static class SingleTonHolder {
        private static final WorkOrderApiService INSTANCE = new WorkOrderApiService();
    }
}
